import React, { useState } from 'react';
import { Card, Button, Space, Input, Row, Col, Select } from 'antd';
import {
  PlusOutlined,
  ImportOutlined,
  ExportOutlined,
  SearchOutlined,
  ReloadOutlined,
  FolderOutlined,
  DesktopOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import './ConnectionsPage.css';
import { ConnectionListComponent } from '@renderer/components/Connections/ConnectionList';
import { ConnectionEditModal } from '@renderer/components/Connections/ConnectionEditModal';
import { useConnectionsStore } from '@renderer/stores/connectionsStore';
import { ConnectionStatus, OsType, PortForwardRule } from '@shared/types';
import { v4 as uuidv4 } from 'uuid';

const { Option } = Select;

const ConnectionsPage: React.FC = () => {
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<ConnectionStatus | null>(null);
  const [osTypeFilter, setOsTypeFilter] = useState<OsType | null>(null);
  const [groupFilter, setGroupFilter] = useState<string | null>(null);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editConnectionId, setEditConnectionId] = useState<string | undefined>(undefined);

  const {
    connections,
    groups,
    setSearchText: storeSetSearchText,
    setFilterStatus,
    setFilterOsType,
    setFilterGroupId,
    exportConnections,
  } = useConnectionsStore();

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
    storeSetSearchText(value);
  };

  // 处理状态筛选
  const handleStatusFilter = (value: ConnectionStatus | '') => {
    setStatusFilter(value || null);
    setFilterStatus(value || null);
  };

  // 处理系统类型筛选
  const handleOsTypeFilter = (value: OsType | '') => {
    setOsTypeFilter(value || null);
    setFilterOsType(value || null);
  };

  // 处理分组筛选
  const handleGroupFilter = (value: string | '') => {
    setGroupFilter(value || null);
    setFilterGroupId(value || null);
  };

  // 处理新建连接
  const handleAddConnection = () => {
    setEditConnectionId(undefined);
    setEditModalVisible(true);
  };

  // 处理导入连接
  const handleImportConnections = async () => {
    try {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.json';

      input.onchange = async (event: any) => {
        const file = event.target.files?.[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = (e) => {
          try {
            const content = e.target?.result as string;
            const importedConnections = JSON.parse(content);

            // 这里应该调用store的importConnections方法
            // mock导入成功
            console.log('导入连接:', importedConnections);

            // 显示成功消息
            window.electronAPI?.dialog.showMessageBox({
              type: 'info',
              title: '导入成功',
              message: `成功导入${importedConnections.length}个连接`,
            });
          } catch (error) {
            console.error('导入失败:', error);
            window.electronAPI?.dialog.showMessageBox({
              type: 'error',
              title: '导入失败',
              message: '文件格式错误',
            });
          }
        };
        reader.readAsText(file);
      };

      input.click();
    } catch (error) {
      console.error('导入失败:', error);
    }
  };

  // 处理导出连接
  const handleExportConnections = async () => {
    try {
      const connections = exportConnections();
      const content = JSON.stringify(connections, null, 2);

      const blob = new Blob([content], { type: 'application/json' });
      const url = URL.createObjectURL(blob);

      const a = document.createElement('a');
      a.href = url;
      a.download = `ssh-connections-${new Date().toISOString().split('T')[0]}.json`;
      a.click();

      URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出失败:', error);
    }
  };

  // 获取筛选后的连接（这里mock一些数据，实际应该从store筛选）
  const filteredConnections = connections;

  return (
    <div className="connections-page">
      <Card
        title="连接管理"
        extra={
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAddConnection}
            >
              新建连接
            </Button>
            <Button icon={<ImportOutlined />} onClick={handleImportConnections}>
              导入
            </Button>
            <Button icon={<ExportOutlined />} onClick={handleExportConnections}>
              导出
            </Button>
          </Space>
        }
        className="connections-card"
      >
        <div className="connections-filters">
          <Row gutter={16}>
            <Col span={12}>
              <Input
                placeholder="搜索连接..."
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => handleSearch(e.target.value)}
                size="large"
                allowClear
              />
            </Col>
            <Col span={12}>
              <Space>
                <Select
                  placeholder="按状态筛选"
                  allowClear
                  onChange={handleStatusFilter }
                  style={{ width: 130 }}
                  suffixIcon={<CheckCircleOutlined />}
                  value={statusFilter || undefined}
                >
                  <Option value="disconnected">
                    <span style={{ display: 'inline-block', width: 8, height: 8, backgroundColor: '#d9d9d9', borderRadius: '50%', marginRight: 8 }}>
                    </span>
                    未连接
                  </Option>
                  <Option value="connecting">
                    <span style={{ display: 'inline-block', width: 8, height: 8, backgroundColor: '#faad14', borderRadius: '50%', marginRight: 8 }}>
                    </span>
                    连接中
                  </Option>
                  <Option value="connected">
                    <span style={{ display: 'inline-block', width: 8, height: 8, backgroundColor: '#52c41a', borderRadius: '50%', marginRight: 8 }}>
                    </span>
                    已连接
                  </Option>
                  <Option value="error">
                    <span style={{ display: 'inline-block', width: 8, height: 8, backgroundColor: '#ff4d4f', borderRadius: '50%', marginRight: 8 }}>
                    </span>
                    连接失败
                  </Option>
                </Select>

                <Select
                  placeholder="按系统筛选"
                  allowClear
                  onChange={handleOsTypeFilter as any}
                  style={{ width: 130 }}
                  suffixIcon={<DesktopOutlined />}
                  value={osTypeFilter || undefined}
                >
                  <Option value="linux">Linux</Option>
                  <Option value="windows">Windows</Option>
                  <Option value="macos">macOS</Option>
                </Select>

                <Select
                  placeholder="按分组筛选"
                  allowClear
                  onChange={handleGroupFilter }
                  style={{ width: 130 }}
                  suffixIcon={<FolderOutlined />}
                  value={groupFilter || undefined}
                >
                  {groups.filter(g => g.id !== 'default').map((group) => (
                    <Option key={group.id} value={group.id}>{group.name}</Option>
                  ))}
                </Select>

                <Button icon={<ReloadOutlined />} onClick={() => {
                  setSearchText('');
                  setStatusFilter(null);
                  setOsTypeFilter(null);
                  setGroupFilter(null);
                  storeSetSearchText('');
                  setFilterStatus(null);
                  setFilterOsType(null);
                  setFilterGroupId(null);
                }}>
                  重置
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        <ConnectionListComponent connections={filteredConnections} />
      </Card>

      <ConnectionEditModal
        visible={editModalVisible}
        onClose={() => setEditModalVisible(false)}
        connectionId={editConnectionId}
      />
    </div>
  );
};

export default ConnectionsPage;